//
//  JCLEmoticonsManager.swift
//  JCLEmoticons
//
//  Created by DDC on 2017/9/25.
//  Copyright © 2017年 DDC. All rights reserved.
//

import Foundation
import UIKit
class JCLEmoticonsManager {
    
    /// 创建单例
    static let shared = JCLEmoticonsManager()
    
    lazy var packages = [JCLEmoticonPackage]()
    /// 私有实例化
    fileprivate init() {
        
        loadPackage()
    }
    
    
}

// MARK: - 查找emoticon图标/表情字符串的处理
extension JCLEmoticonsManager {
    
    
    /// 表情字符串的处理
    ///
    /// - Parameters:
    ///   - string: 需要处理的文字
    ///   - font: 显示的字体大小
    /// - Returns: 返回一个表情字符串
    func emoticonString (string:String, font:UIFont)-> NSAttributedString {
        
        let attrString = NSMutableAttributedString(string: string)
        /// 匹配规则
        let pattern = "\\[.*?\\]"
        /// 建立正则表达式,过滤所有的表情字符串
        guard let regx = try? NSRegularExpression(pattern: pattern, options: []) else {
            return attrString
        }
        /// 匹配所有项
        let result = regx.matches(in: string, options: [], range: NSRange(location: 0, length: attrString.length))
        /// 要按照匹配倒序替换属性文本
        for m in result.reversed() {
            
            let r = m.rangeAt(0)
            
            let subStr = (attrString.string as NSString).substring(with: r)
            
            
            if let emo = JCLEmoticonsManager.shared.findEmoticon(string: subStr){
                attrString.replaceCharacters(in: r, with: emo.imageText(textFont: font))
            }
        }
        // 统一设置一遍字符串的属性 
        attrString.addAttributes([NSFontAttributeName: font], range: NSRange(location: 0, length: attrString.length))
        
        return attrString
        
    }
    
    /// 查找表情字符串
    ///
    /// - Parameter string:
    /// - Returns:
    func findEmoticon(string:String) -> JCLEmoticon? {
        
        for model in packages {
            
            let result = model.emoticons.filter({ (emo) -> Bool in
                return emo.chs == string
            })
            if result.count == 1 {
                return result[0]
            }
        }
       return nil
    }
    

}

// MARK: - 加载bundle数据
extension JCLEmoticonsManager {
    
    func loadPackage() {
        
       guard
        let path = Bundle.main.path(forResource: "Emoticons.bundle", ofType: nil),
        let bundle = Bundle(path: path) ,
        let plistPath = bundle.path(forResource: "emoticons.plist", ofType: nil),
        let array = NSArray.init(contentsOfFile: plistPath) as? [[String:String]],
        let models = NSArray.yy_modelArray(with: JCLEmoticonPackage.self, json: array) as? [JCLEmoticonPackage]
        else {
            return
        }
        
        packages += models
        
        
    }
    
}

// MARK: - 最近按钮的排序显示
extension JCLEmoticonsManager {
    
    func recentEmoticon(emo:JCLEmoticon) {
        
        // 记录emoticon的点击次数
        emo.times += 1
        // 检查“最近”模型中是否包含该模型
        if !packages[0].emoticons.contains(emo) {
            packages[0].emoticons.append(emo)
        }
        // 排序
        packages[0].emoticons.sort { (emo1, emo2) -> Bool in
            
            return emo1.times > emo2.times
        }
        // 删除超过20的个数的表情模型
        if packages[0].emoticons.count > 20 {
            packages[0].emoticons.removeSubrange(20..<packages[0].emoticons.count)
        }
        
    }
}
